package com.objectechenica.java.ui;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;

import com.objectechenica.java.net.ImageDownloader;

public class ImageDownloadScreen extends LoaderScreen implements DownloadListener{
	ImageDownloadScreen activeScreen = null;
	
	public ImageDownloadScreen() {
		setTitle("Download Image");
		
		ButtonField btn = new ButtonField("Click to Download", ButtonField.CONSUME_CLICK) {
			protected boolean navigationClick(int arg0, int arg1) {
				setShowLoader(true);
				//starting download thread
				ImageDownloader download = new ImageDownloader("http://www.ciracar.com/img/girls/cute_selena_gomez/cute_selena_gomez7.jpg");
				
				download.setDelegate(activeScreen);
				
				//Starting download thread
				new Thread(download).start();				
				return true;
			}
		};
		
		//adding button to screen
		add(btn);
		
		//getting the reference of active screen
		activeScreen = this;
	}
	
	// Method to perform all the UI activity, like update to UI if the download success
	public void downloadSuccess(final Bitmap bitmap) {
		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				setShowLoader(false);
				if (bitmap == null) {
					Dialog.alert("Failed to download Image");
				} else {
					try {
						BitmapField image = new BitmapField(bitmap);
						activeScreen.add(image);
					} catch (Exception e) {
						Dialog.alert("Got error: " + e);
					}
				}
			}
		});
	}

	//display error message if error in download
	public void errorOccured() {
		//Currently not being used
		Dialog.alert("Failed to download Image");
	}
}
